<script setup lang="ts">
import { computed, ref } from 'vue'
import type { MedicineDetail } from '@/types/medicine'
import { MedicineC } from '@/types/medicine.d'
import { deleteOssImg, getMedicineDetail, saveMedicine, updateMedicine } from '@/services/medicine'
import { onLoad } from '@dcloudio/uni-app'

const query = defineProps<{
  id: number
}>()

const formData = ref<MedicineDetail>(new MedicineC())

onLoad( async () => {
  if (query.id) {
    formData.value = await getMedicineDetail(query.id)
  }
  await uni.setNavigationBarTitle({ title: query.id ? '修改药品' : '新增药品' })
})

const medicineImgs = computed(() => {
  return formData.value.medicineImgs.map(url => {
    return { url }
  })
})
const specificationImgs = computed(() => {
  return formData.value.specificationImgs.map(url => {
    return { url }
  })
})

const form = ref()

/**
 * 触发表单提交
 */
function submit() {
  uni.showToast({
    title: '数据保存中...', icon: 'none',
  })
  console.log('save medicine: ', formData.value)
  // submitForm()
}

async function submitForm() {
  if (formData.value.id) {
    await updateMedicine(formData.value)
  } else {
    await saveMedicine(formData.value)
  }
  await uni.showToast({
    title: '药品数据保存成功', icon: 'success',
  })
  setTimeout(() => uni.navigateBack(), 500)
}

const isOnSaleChange: UniHelper.SwitchOnChange = (ev) => {
  formData.value.isOnSale = ev.detail.value ? 1 : 0
}

function selectedImgs(e: UniHelper.UniFilePickerOnSelectEvent, imgUrls: string[]) {
  for (let tempFilePath of e.tempFilePaths) {
    uploadFile(tempFilePath, imgUrls)
  }
}
function uploadFile(tempFilePath: string, imgUrls: string[]) {
  uni.uploadFile({
    url: '/medicine/oss/upload', name: 'file', filePath: tempFilePath, success: (res) => {
      if (res.statusCode === 200) {
        imgUrls.push(JSON.parse(res.data).data)
      }
    },
  })
}
function delImg(e: UniHelper.UniFilePickerOnDeleteEvent, imgUrls: string[]) {
  deleteOssImg(e.tempFilePath)
  imgUrls.splice(imgUrls.indexOf(e.tempFilePath), 1)
}
</script>

<template>
  <view class="container">
    <view class="uni-container">
      <uni-forms class="" ref="form" :value="formData" validate-trigger="submit" err-show-type="toast">
        <uni-forms-item name="medicineImgs" label="药品外包装图片">
          <uni-file-picker v-model="medicineImgs"
                           @select="selectedImgs($event, formData.medicineImgs)"
                           @delete="delImg($event, formData.medicineImgs)"
                           mode="grid" :limit="3" file-mediatype="image"
          />
        </uni-forms-item>

        <uni-forms-item name="specificationImg" label="药品说明书图片">
          <uni-file-picker v-model="specificationImgs"
                           @select="selectedImgs($event, formData.specificationImgs)"
                           @delete="delImg($event, formData.specificationImgs)"
                           mode="grid" :limit="2" file-mediatype="image"
          />
        </uni-forms-item>

        <uni-forms-item name="medicineName" label="药品名" required>
          <uni-easyinput placeholder="药品名" v-model="formData.medicineName" trim="both"></uni-easyinput>
        </uni-forms-item>
        <uni-forms-item name="genericName" label="通用名">
          <uni-easyinput placeholder="通用名" v-model="formData.genericName" trim="both"></uni-easyinput>
        </uni-forms-item>
        <uni-forms-item name="medicineType" label="药品类型">
          <uni-easyinput placeholder="药品类型" v-model="formData.medicineType" trim="both"></uni-easyinput>
        </uni-forms-item>
        <uni-forms-item name="specificationPackaging" label="规格包装">
          <uni-easyinput placeholder="规格包装" v-model="formData.specificationPackaging" trim="both"></uni-easyinput>
        </uni-forms-item>
        <uni-forms-item name="price" label="单价">
          <uni-easyinput placeholder="单价" type="number" v-model="formData.price"></uni-easyinput>
        </uni-forms-item>
        <uni-forms-item name="medicineForm" label="剂型">
          <uni-easyinput placeholder="剂型" v-model="formData.medicineForm" trim="both"></uni-easyinput>
        </uni-forms-item>
        <uni-forms-item name="medicineForm" label="包装单位">
          <uni-easyinput placeholder="盒/瓶/包/袋 等" trim="both"></uni-easyinput>
        </uni-forms-item>
        <uni-forms-item name="usageDosage" label="用法用量">
          <uni-easyinput
            v-model="formData.usageDosage"
            placeholder="例如：口服，一次20mg，一日3次"
            trim="both">
          </uni-easyinput>
        </uni-forms-item>
        <uni-forms-item name="treatmentCourse" label="疗程">
          <uni-easyinput placeholder="例如：三个月" v-model="formData.treatmentCourse" trim="both"></uni-easyinput>
        </uni-forms-item>
        <uni-forms-item name="manufacturer" label="厂家">
          <uni-easyinput placeholder="生产厂家" v-model="formData.manufacturer" trim="both"></uni-easyinput>
        </uni-forms-item>
        <uni-forms-item name="approvalNumber" label="批准文号">
          <uni-easyinput placeholder="批准文号" v-model="formData.approvalNumber" trim="both"></uni-easyinput>
        </uni-forms-item>
        <uni-forms-item name="productionDate" label="生产日期">
          <uni-datetime-picker type="date" placeholder="选择药品生产日期" return-type="date"
                               v-model="formData.productionDate">
          </uni-datetime-picker>
        </uni-forms-item>
        <uni-forms-item name="validUntil" label="有效期至">
          <uni-datetime-picker type="date" placeholder="选择药品有效期至" return-type="date"
                               v-model="formData.validUntil">
          </uni-datetime-picker>
        </uni-forms-item>
        <uni-forms-item name="isOnSale" label="是否上架">
          <switch
            @change="isOnSaleChange"
            :checked="formData.isOnSale === 1"
            color="#27ba9b"
          />
        </uni-forms-item>
      </uni-forms>
    </view>

    <button @click="submit" type="warn">提交</button>
  </view>
</template>

<style lang="scss">
.container {
  .uni-container {
    margin-bottom: 50px;
  }

  button {
    line-height: 2;
    font-size: 16px;
    // background-color: #00e676;
    position: fixed;
    bottom: 5px;
    left: 20px;
    right: 10px;
    border-radius: 20px;
  }
}

.uni-container {
  background-color: #FFFFFF;
  padding: 15px;
}

.uni-input-border,
.uni-textarea-border {
  width: 100%;
  font-size: 14px;
  color: #666;
  border: 1px #e5e5e5 solid;
  border-radius: 5px;
  box-sizing: border-box;
}

.uni-input-border {
  padding: 0 10px;
  height: 35px;

}

.uni-textarea-border {
  padding: 10px;
  height: 80px;
}

.uni-button-group {
  margin-top: 50px;
  /* #ifndef APP-NVUE */
  display: flex;
  /* #endif */
  justify-content: center;
}

.uni-button {
  width: 184px;
  padding: 12px 20px;
  font-size: 14px;
  border-radius: 4px;
  line-height: 1;
  margin: 0;
}
</style>
